<template>
  <div>
    <div id="panel">
      <button @click="goToHome">返回主页</button>
      <hr>
      <label>我的地址：</label>
      <input id="start" type="text" placeholder="如 昆明南站">
      <button @click="useCurrentLocation">使用当前位置</button><br><br>
      <button @click="moveToCurrentLocation">回到当前位置</button><br><br>

      <label>导航方式：</label><br>
      <label class="mode"><input type="radio" name="mode" value="walk" checked> 步行</label>
      <label class="mode"><input type="radio" name="mode" value="drive"> 驾车</label>
      <label class="mode"><input type="radio" name="mode" value="transit"> 公交</label><br><br>

      <label>搜索附近：</label>
      <input id="keyword" type="text" placeholder="如 酒店/餐厅/超市">
      <button @click="searchNearby">搜索</button><br><br>

      <label>分类快捷筛选：</label><br>
      <button @click="searchByCategory('酒店')">酒店</button>
      <button @click="searchByCategory('餐厅')">餐厅</button>
      <button @click="searchByCategory('超市')">超市</button>
      <button @click="searchByCategory('医院')">医院</button>

      <div id="results"></div>
    </div>

    <div id="container"></div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'

let map, local, startPoint, centerPoint
let currentRange = 5000

import { useRouter } from 'vue-router'  // 添加路由导入

const router = useRouter()  // 获取路由实例

// 添加导航方法
function goToHome() {
  router.push('/')
}
onMounted(() => {
  if (!document.getElementById('baidu-map-script')) {
    const script = document.createElement('script')
    script.id = 'baidu-map-script'
    script.src = 'https://api.map.baidu.com/api?v=3.0&type=webgl&ak=F1HTcXXaXIlbjdwO8hoZKXgJp1ZnQVAe'
    script.async = true
    script.onload = () => {
      centerPoint = new BMapGL.Point(102.8414, 24.8897) // 初始：昆明呈贡
      initMap()
    }
    document.head.appendChild(script)
  } else {
    centerPoint = new BMapGL.Point(102.8414, 24.8897)
    initMap()
  }
})

function initMap() {
  map = new BMapGL.Map("container")
  map.centerAndZoom(centerPoint, 15)
  map.enableScrollWheelZoom(true)
  map.addControl(new BMapGL.ScaleControl())
  map.addControl(new BMapGL.ZoomControl())

  local = new BMapGL.LocalSearch(map, {
    renderOptions: { map: map },
    onSearchComplete: onSearchComplete
  })

  enableAutocomplete("start")
}

function onSearchComplete(results) {
  const resultDiv = document.getElementById("results")
  resultDiv.innerHTML = ""
  if (local.getStatus() === BMAP_STATUS_SUCCESS) {
    for (let i = 0; i < results.getCurrentNumPois(); i++) {
      const poi = results.getPoi(i)
      const item = document.createElement("div")
      item.className = "result-item"
      item.textContent = poi.title + " - " + poi.address
      item.onclick = () => navigateTo(poi.point)
      resultDiv.appendChild(item)
    }
  } else {
    resultDiv.innerHTML = "<div>未找到相关地点。</div>"
  }
}

function updateSearchRange(event) {
  currentRange = parseInt(event.target.value)
}

function searchNearby() {
  const keyword = document.getElementById("keyword").value
  local.searchNearby(keyword, centerPoint, currentRange)
  local.setPageCapacity(20)
}

function searchByCategory(category) {
  document.getElementById("keyword").value = category
  local.searchNearby(category, centerPoint, currentRange)
}

function geocode(address) {
  return new Promise((resolve, reject) => {
    const geo = new BMapGL.Geocoder()
    geo.getPoint(address, function (point) {
      if (point) {
        resolve(point)
      } else {
        reject("无法解析地址: " + address)
      }
    })
  })
}

async function navigateTo(destPoint) {
  map.clearOverlays()
  if (!startPoint) {
    const addr = document.getElementById("start").value
    try {
      startPoint = await geocode(addr)
    } catch (err) {
      alert(err)
      return
    }
  }

  map.addOverlay(new BMapGL.Marker(startPoint))
  map.addOverlay(new BMapGL.Marker(destPoint))

  const mode = document.querySelector('input[name="mode"]:checked').value
  let route
  if (mode === "walk") {
    route = new BMapGL.WalkingRoute(map, {renderOptions: {map: map, autoViewport: true}})
  } else if (mode === "drive") {
    route = new BMapGL.DrivingRoute(map, {renderOptions: {map: map, autoViewport: true}})
  } else if (mode === "transit") {
    route = new BMapGL.TransitRoute(map, {renderOptions: {map: map, autoViewport: true}})
  }

  route.search(startPoint, destPoint)

  route.setSearchCompleteCallback(function (results) {
    if (route.getStatus() === BMAP_STATUS_SUCCESS) {
      const plan = results.getPlan(0)
      const duration = plan.getDuration(true)
      const distance = plan.getDistance(true)

      const resultDiv = document.getElementById("results")
      const info = document.createElement("div")
      info.className = "highlight-info"
      info.textContent = `预计用时：${duration} | 距离：${distance}`

      const old = document.querySelector(".highlight-info")
      if (old) old.remove()

      resultDiv.insertBefore(info, resultDiv.firstChild)
    }
  })
}

function enableAutocomplete(id) {
  const ac = new BMapGL.Autocomplete({
    input: id,
    location: centerPoint
  })
  ac.addEventListener("onconfirm", function (e) {
    const _value = e.item.value
    const fullAddr = _value.province + _value.city + _value.district + _value.street + _value.business
    document.getElementById(id).value = fullAddr
    startPoint = null
  })
}

function useCurrentLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (pos) {
      const lng = pos.coords.longitude
      const lat = pos.coords.latitude
      startPoint = new BMapGL.Point(lng, lat)
      centerPoint = startPoint

      document.getElementById("start").value = "我的当前位置"

      // 清除并标记当前位置
      map.clearOverlays()
      const marker = new BMapGL.Marker(startPoint)
      map.addOverlay(marker)
      map.panTo(startPoint)

      // 自动搜索当前位置附近
      const keyword = document.getElementById("keyword").value || "酒店"
      local.searchNearby(keyword, centerPoint, currentRange)
      local.setPageCapacity(20)

      alert("当前位置设置成功，已自动搜索附近 " + keyword)
    }, function (err) {
      alert("定位失败：" + err.message)
    })
  } else {
    alert("浏览器不支持定位功能")
  }
}

function moveToCurrentLocation() {
  if (startPoint) {
    map.panTo(startPoint)
    map.setZoom(16)
  } else {
    alert("请先点击“使用当前位置”进行定位")
  }
}
</script>

<style scoped>
#container {
  height: 100vh;
}

#panel {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
  background: white;
  border-radius: 10px;
  padding: 20px;
  width: 360px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  font-family: "Segoe UI", "Helvetica Neue", sans-serif;
}

input[type="text"], select {
  width: 100%;
  padding: 8px;
  font-size: 14px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 6px;
}

button {
  padding: 8px 12px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  margin: 3px;
}

button:hover {
  background-color: #005bb5;
}

.mode {
  display: inline-block;
  margin-right: 10px;
}

#results {
  max-height: 220px;
  overflow-y: auto;
  margin-top: 12px;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.result-item {
  padding: 8px;
  margin-bottom: 4px;
  border-radius: 5px;
  background-color: #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.result-item:hover {
  background-color: #e0e0e0;
}

.highlight-info {
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 8px;
  background-color: #e9f5ff;
  padding: 6px;
  border-radius: 5px;
}
</style>